package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.CustomerTransfer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.mapper.CustomerTransferMapper;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.ICustomerTransferService;
import cn.wolfcode.crm.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerTransferServiceImpl implements ICustomerTransferService {

    @Autowired
    private CustomerTransferMapper customerTransferMapper;

    @Autowired
    private CustomerMapper customerrMapper;

    public void delete(Long id) {
        customerTransferMapper.deleteByPrimaryKey(id);
    }

    public void save(CustomerTransfer customerTransfer) {

        //根据移交历史对象的信息 把该客户的销售人员  改成新的销售人员
        Long sellerId = customerTransfer.getNewseller().getId();
        Long customerId = customerTransfer.getCustomer().getId();
        customerrMapper.changeSeller(sellerId, customerId);

        //设置跟进操作的操作人 录入时间
        Employee employee = UserContext.getCurrentUser();
        customerTransfer.setOperateTime(new Date());
        customerTransfer.setOperator(employee);

        customerTransferMapper.insert(customerTransfer);
    }

    public CustomerTransfer get(Long id) {
        return customerTransferMapper.selectByPrimaryKey(id);
    }

    public List<CustomerTransfer> listAll() {
        return customerTransferMapper.selectAll();
    }

    public void update(CustomerTransfer customerTransfer) {
        customerTransferMapper.updateByPrimaryKey(customerTransfer);
    }

    @Override
    public PageInfo<CustomerTransfer> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<CustomerTransfer> customerTransfers = customerTransferMapper.query(qo);
        return new PageInfo(customerTransfers);
    }

    @Override
    public void gainCustomer(CustomerTransfer customerTransfer) {
        //获取当前登录用户 id
        Long userId = UserContext.getCurrentUser().getId();
        // 因为是吸纳 把该客户的销售人员  改成当前登录用户
        Long customerId = customerTransfer.getCustomer().getId();
        customerrMapper.changeSeller(userId, customerId);


        //设置跟进操作的操作人 录入时间
        Employee employee = UserContext.getCurrentUser();
        customerTransfer.setOperateTime(new Date());
        customerTransfer.setOperator(employee);

        //前端没有传新销售人 所有在后端进行赋值 把当前登录用户作为 新销售人
        customerTransfer.setNewseller(UserContext.getCurrentUser());

        //把当前被吸纳的用户 修改状态 成潜在用户
        customerrMapper.changeStatus(Customer.STATUS_POTENTIAL, customerTransfer.getCustomer().getId());

        customerTransferMapper.gainCustomer(customerTransfer);
    }

}
